const Joi = require("joi");

let BikeSchema = Joi.object({
    name: Joi.string().required().error(new Error('name参数填写错误')),
    marketTime: Joi.string().required().error(new Error('marketTime参数填写错误')),
    brandId: Joi.number().required().error(new Error('brandId参数填写错误')),
    img: Joi.string().required().error(new Error('img参数填写错误')),
    detailParams: Joi.string().required().error(new Error('detailParams参数填写错误')),
    price: Joi.number().required().error(new Error('price参数填写错误')),
    bikeType: Joi.string().required().error(new Error('brand参数填写错误')),
    bikeTags: Joi.string().error(new Error('bikeTags参数填写错误')),
});

class BikeMiddleware {
    async bikeValidator(ctx, next) {
        const bodyParams = ctx.request.body;
        const {id} = ctx.params;
        if (ctx.request.url.indexOf('update') > -1) {
            if (!id) {
                return ctx.body = {
                    status: 1,
                    msg: '未传菜单id'
                }
            }
        }
        if (bodyParams) {
            const {error} = BikeSchema.validate(bodyParams, {
                abortEarly: true
            });
            if (error) {
                console.log(error)
                return ctx.body = {
                    status: 1,
                    msg: error.message
                }
            }
        } else {
            return ctx.body = {
                status: 1,
                msg: '请填写必填参数'
            }
        }
        await next()
    }
}

module.exports = new BikeMiddleware();
